import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: "*",
    redirect:"login"
  },
  {
    path: "/index",
    component: () => import("../pages/index/index.vue"),meta:{title:"小U商城"},
    children: [
      { path: "home", component: () => import("../pages/home/home.vue"), meta: { title: "小U商城" } },
      { path: "cate", component: () => import("../pages/cate/cate.vue"), meta: { title: "商品分类" } },
      { path: "shop", component: () => import("../pages/shop/shop.vue") , meta: { title: "购物车" }},
      { path: "mine", component: () => import("../pages/mine/mine.vue") , meta: { title: "个人中心" }},
      { path: "", redirect:"home" }
    ]
  },
  {
    path: "/list",
    component: () => import("../pages/list/list.vue"),meta:{title:"商品列表"}
  },
  {
    path: "/detail/:id",
    component: () => import("../pages/detail/detail.vue"),meta:{title:"商品详情"}
  },
  {
    path: "/search",
    component: () => import("../pages/search/search.vue"),meta:{title:"商品搜索"}
  },
  {
    path: "/order",
    component: () => import("../pages/order/order.vue"),meta:{title:"确认订单"}
  },
  {
    path: "/login",
    component: () => import("../pages/login/login.vue"),meta:{title:"手机登录"}
  },
  {
    path: "/register",
    component: () => import("../pages/register/register.vue"),meta:{title:"账号注册"}
  },
  {
    path: "/addressAdd",
    component: () => import("../pages/addressAdd/addressAdd.vue"),meta:{title:"添加地址"}
  },
  {
    path: "/addressList",
    component: () => import("../pages/addressList/addressList.vue"),meta:{title:"地址列表"}
  },
  {
    path: "/pay",
    component: () => import("../pages/pay/pay.vue"),meta:{title:"地址列表"}
  },
]

const router = new VueRouter({
  routes,
  scrollBehavior(to,from,savePosition){
    if(savePosition){
      return savePosition
    }else{
      return {x:0,y:0}
    }
  }
})

// 全局守卫
router.beforeEach((to,from,next)=>{
  // console.log("全局前置守卫 beforeEach");
  // console.log(to,from,next);
  // 1.去登录或者注册页面直接进
  if(to.path==="/login"||to.path==="/register"){
    next();
    return;
  }
  // 如果不是登录页面，判断是否有islogin，有就放行，
  let islogin=localStorage.getItem("islogin")
  if(islogin){
    next()
    return
  }
  // 没有islogin就去登录
  next("/login")
})

export default router
